package com.taoli.api;

import com.taoli.common.DetailType;
import com.taoli.common.Result;
import com.taoli.entity.BalanceDetail;
import com.taoli.entity.Wallet;
import com.taoli.service.BalanceDetailService;
import com.taoli.service.WalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
* @Description: 用户控制器
* @author: 韦武朝
* @date: 2023/2/16 20:46
*/
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private WalletService walletService;
    @Autowired
    private BalanceDetailService balanceDetailService;

    /**
    * @Description:  1、查询用户钱包余额
    * @author: 韦武朝
    * @date: 2023/2/16 16:22
    * @param userId:用户ID
    * @Return: com.taoli.entity.Wallet
    */
    @GetMapping("/getBalance")
    public Map<String, Object> getBalance(@RequestParam Long userId){
        Wallet wallet = walletService.getBalanceByUserId(userId);
        if (wallet == null) return Result.failure("用户不存在！");
        else return Result.success(wallet);
    }

    /**
    * @Description: 2、用户消费100元的接口
    * @author: 韦武朝
    * @date: 2023/2/16 16:46
     * @Return: java.util.Map<java.lang.String,java.lang.Object>
    */
    @PostMapping("/consume")
    @Transactional
    public Map<String,Object> consume(@RequestParam Long userId){
        Wallet wallet = walletService.getBalanceByUserId(userId);
        if(wallet == null) return Result.failure("用户不存在");
        Double balance = wallet.getBalance();
        Double consumeMoney = 100.0;
        if(balance.doubleValue() >= consumeMoney.doubleValue()) {
            Double beforeBalance = wallet.getBalance();
            wallet.setBalance(wallet.getBalance() - consumeMoney);
            wallet = walletService.save(wallet);
            Double afterBalance = wallet.getBalance();

            BalanceDetail balanceDetail = getSaveBalanceDetail(userId, DetailType.CONSUME, consumeMoney, beforeBalance, afterBalance);
            balanceDetail = balanceDetailService.save(balanceDetail);
            if (balanceDetail != null) return Result.success();
        }
        return Result.failure("余额不足！");
    }
    /**
    * @Description: 用户退款20元接口
    * @author: 韦武朝
    * @date: 2023/2/16 17:31
    * @param userId: 用户ID
    * @Return: java.util.Map<java.lang.String,java.lang.Object>
     *
    */
    @PostMapping("/refund")
    @Transactional
    public Map<String,Object> refund(@RequestParam Long userId){
        Wallet wallet = walletService.getBalanceByUserId(userId);
        if(wallet == null) return Result.failure("用户不存在!");
        Double refundMoney = 20.0;
        Double beforeBalance = wallet.getBalance();
        wallet.setBalance(wallet.getBalance() + refundMoney);
        wallet = walletService.save(wallet);
        Double afterBalance = wallet.getBalance();

        BalanceDetail balanceDetail = getSaveBalanceDetail(userId, DetailType.REFUND,refundMoney, beforeBalance, afterBalance);
        balanceDetail = balanceDetailService.save(balanceDetail);
        if(balanceDetail != null) return Result.success();
        else return Result.failure();
    }

    /**
    * @Description: 4、查询用户钱包金额变动明细的接口
    * @author: 韦武朝
    * @date: 2023/2/16 17:39
    * @param userId: 用户ID
    * @param pageSize: 页大小
     * @param pageNumber: 页码
     * @Return: java.util.Map<java.lang.String,java.lang.Object>
     *      data.detailList 分页数据
     *          detailList[n].detailId 明细ID
     *          detailList[n].userId 用户id
     *          detailList[n].type 明细类型： 1、充值 2、退款 3、消费 4、提现
     *          detailList[n].changeMoney 变动金额
     *          detailList[n].beforeBalance 变动前余额
     *          detailList[n].afterBalance 变动后余额
     *          detailList[n].creationDate 创建日期
     *      totalPages 总页数
     *      totalElements 总记录数
     *      currentPageNumber 当前页数
     *      currentPageSize 当前页大小
    */
    @GetMapping("/getBalanceDetailList")
    public Map<String,Object> getBalanceDetailList(@RequestParam Long userId, @RequestParam(defaultValue = "2") Integer pageSize,@RequestParam(defaultValue = "1")Integer pageNumber){
        Wallet wallet = walletService.getBalanceByUserId(userId);
        if(wallet == null) return Result.failure("用户不存在！");
        if(pageNumber < 1) pageNumber = 1;
        Page<BalanceDetail> pageData = balanceDetailService.getBalanceDetailList(userId,pageSize,pageNumber);
        List<BalanceDetail> detailList = pageData.getContent();
        int totalPages = pageData.getTotalPages(); // 总页数
        long totalElements = pageData.getTotalElements();// 总条数
        int currentPageNumber = pageData.getPageable().getPageNumber()+1;// 当前页数
        int currentPageSize = pageData.getPageable().getPageSize(); // 当前页大小
        Map<String, Object> map = Result.success();

        Map<String,Object> data = new LinkedHashMap<>();
        data.put("detailList",detailList);
        data.put("totalPages",totalPages);
        data.put("totalElements",totalElements);
        data.put("currentPageNumber",currentPageNumber);
        data.put("currentPageSize",currentPageSize);

        map.put("data",data);
        return map;
    }

    /**
    * @Description: 获取保存余额明细对象
    * @author: 韦武朝
    * @date: 2023/2/16 21:03
    * @param userId: 用户ID
    * @param changeMoney: 变动金额
    * @param beforeBalance: 变动前金额
    * @param afterBalance: 变动后金额
    * @Return: com.taoli.entity.BalanceDetail
    */
    private static BalanceDetail getSaveBalanceDetail(Long userId,Integer type,Double changeMoney,Double beforeBalance,Double afterBalance){
        BalanceDetail balanceDetail = new BalanceDetail();
        balanceDetail.setUserId(userId);
        balanceDetail.setType(type);
        balanceDetail.setChangeMoney(changeMoney);
        balanceDetail.setBeforeBalance(beforeBalance);
        balanceDetail.setAfterBalance(afterBalance);
        balanceDetail.setCreationDate(new Date());
        return balanceDetail;
    }

}
